package com.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
/**
 * 
 * HTTP工具类
 * @author  HuYaHui
 * @version $Revision:1.0.0, $Date: 2015年9月24日 下午9:10:57 $ 
 *
 */
public class HttpClientUtil {
	public static final String UTF8="UTF-8";

	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
	public static void main(String[] args) throws Exception {
		
		String url="http://127.0.0.1:8089/mail/sendMail";
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("to", "307575240@qq.com");
		params.put("type", "TEXT");
		params.put("title", "s");
		params.put("content", "xxx");
		params.put("fromNickName", "nn");
		params.put("fromAddress", "service@shanlin.com");

		String name="user";
		String pwd="secret";
		System.out.println(postDataByHTTP(url, params, name, pwd));

	}
	
	public static String getDataByHTTP(String url) throws Exception { 
		return getDataByHTTP(url,10000,null,null);
	}
	
	/**
	 * get获取资源
	 * @param url
	 * @param timeout
	 * @return
	 * @throws Exception
	 */
	public static String getDataByHTTP(String url,int timeout
			,String name,String pwd) throws Exception { 
		if(StringUtils.isBlank(url)){
			throw new Exception("url不能为空!");
		}
		long start=System.currentTimeMillis();
		CloseableHttpClient httpClient =null;
		HttpGet httpget=null;
		try {
			RequestConfig requestConfig=HttpClientFactory.getRequestConfig(timeout);		
			httpClient = HttpClientFactory.getDefaultHttpClient(url, requestConfig);
			httpget = new HttpGet(url);
			httpget.setConfig(RequestConfig.copy(requestConfig).build());
			return getData(url,httpClient,httpget,name,pwd);
		} catch (Exception e) {
			
			log.error("http请求获取数据异常，url："+url+",耗时："+(System.currentTimeMillis()-start),e);
		}finally{
			httpget.releaseConnection();
			httpget.abort();
			httpClient.close();
		}
		return "";
	}
	
	public static String postDataByHTTP(String url,Map<String,Object> params
			,String name,String pwd) throws Exception {
		return postDataByHTTP(url, params, 60000,name,pwd);
	}
	
	/**
	 * post获取数据
	 * @param url
	 * @param params
	 * @param timeout
	 * @param name
	 * @param pwd
	 * @return
	 * @throws Exception
	 */
	public static String postDataByHTTP(String url,Map<String,Object> params, int timeout
			,String name,String pwd) throws Exception { 
		if(StringUtils.isBlank(url)){
			throw new Exception("url不能为空!");
		}
		long start=System.currentTimeMillis();
		RequestConfig requestConfig=HttpClientFactory.getRequestConfig(timeout);
		CloseableHttpClient httpClient = HttpClientFactory.getDefaultHttpClient(url, requestConfig);
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response =null;
		try {
			StringEntity entity = new StringEntity(JSONObject.toJSONString(params), UTF8);
			httpPost.setEntity(entity);
			entity.setContentType("application/json");

			if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(pwd)){
				byte[] byte64=org.apache.commons.codec.binary.Base64.encodeBase64((name+":"+pwd).getBytes());
				String aut="Basic "+new String(byte64);
				httpPost.setHeader("Authorization", aut);
			}
			
			httpPost.setConfig(RequestConfig.copy(requestConfig).build());
			response = httpClient.execute(httpPost);
			HttpEntity entityRep = response.getEntity();
			if (entityRep != null) {
				Header ceheader = entityRep.getContentEncoding();
				if (ceheader != null) {
					for (HeaderElement element : ceheader.getElements()) {
						if (element.getName().equalsIgnoreCase("gzip")) {
							response.setEntity(new GzipDecompressingEntity(response.getEntity()));
							break;
						}else if(element.getName().equalsIgnoreCase("deflate")){
							response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
							break;
						}
					}
				}

				String str="";
				if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && entityRep != null) {
					str=EntityUtils.toString(response.getEntity(),UTF8);
				}else{
					log.debug(url+"连接异常:"+response.getStatusLine().getStatusCode());
				}
				EntityUtils.consume(response.getEntity());
				return str;
			}
		} catch (Exception e) {
			log.error("http请求获取数据异常，url："+url+",耗时："+(System.currentTimeMillis()-start),e);
		}finally {
			if(response!=null){
				response.close();
			}
			httpPost.releaseConnection();
			httpPost.abort();
			httpClient.close();
		}
		return "";
	}
	
	private static String getData(String url,CloseableHttpClient httpClient,HttpGet httpget
			,String name,String pwd) throws Exception { 
		if(StringUtils.isBlank(url)){
			throw new Exception("url不能为空!");
		}
		long start=System.currentTimeMillis();
		CloseableHttpResponse response =null;
		try {
			if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(pwd)){
				byte[] byte64=org.apache.commons.codec.binary.Base64.encodeBase64((name+":"+pwd).getBytes());
				String aut="Basic "+new String(byte64);
				httpget.setHeader("Authorization", aut);
			}

			response = httpClient.execute(httpget);
			HttpEntity resEntity = response.getEntity();
			if(resEntity!=null){
				Header ceheader = resEntity.getContentEncoding();
				if (ceheader != null) {
					for (HeaderElement element : ceheader.getElements()) {
						if (element.getName().equalsIgnoreCase("gzip")) {
							response.setEntity(new GzipDecompressingEntity(response.getEntity()));
							break;
						}else if(element.getName().equalsIgnoreCase("deflate")){
							response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
							break;
						}
					}
				}
				String str="";
				if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && resEntity != null) {
					str=EntityUtils.toString(response.getEntity(),UTF8);
				}else{
					log.debug(url+"连接异常:"+response.getStatusLine().getStatusCode());
				}
				EntityUtils.consume(response.getEntity());
				return str;
			}
		} catch (Exception e) {
			log.error("http请求获取数据异常，url："+url+",耗时："+(System.currentTimeMillis()-start),e);
		} finally {
			if(response!=null){
				response.close();
			}
		}
		return "";
	}
}
